package cn.heyige.backend.facade;

import cn.heyige.backend.dto.EmailDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 邮件服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailFacade {
    
    private final JavaMailSender mailSender;
    
    /**
     * 发送简单邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    @Async
    public void sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("邮件发送成功: 收件人={}, 主题={}", to, subject);
        } catch (Exception e) {
            log.error("邮件发送失败: 收件人={}, 主题={}", to, subject, e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }
    
    /**
     * 发送API KEY异常提醒邮件
     * @param emailDto 邮件数据传输对象
     */
    @Async
    public void sendApiKeyAlertEmail(EmailDto.ApiKeyAlertEmailDto emailDto) {
        String subject = "【AI聊天系统】API KEY异常提醒";
        
        StringBuilder content = new StringBuilder();
        content.append("尊敬的管理员：\n\n");
        content.append("系统检测到API KEY异常，请及时处理。\n\n");
        content.append("异常详情：\n");
        content.append("--------------------------------------------------\n");
        content.append("服务名称：").append(emailDto.getServiceName()).append("\n");
        content.append("异常类型：").append(emailDto.getErrorType()).append("\n");
        content.append("异常时间：").append(emailDto.getErrorTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        content.append("异常描述：").append(emailDto.getErrorDescription()).append("\n");
        
        if (emailDto.getAdditionalInfo() != null && !emailDto.getAdditionalInfo().isEmpty()) {
            content.append("附加信息：").append(emailDto.getAdditionalInfo()).append("\n");
        }
        
        content.append("--------------------------------------------------\n\n");
        content.append("请尽快检查相关配置和服务状态。\n\n");
        content.append("此邮件由系统自动发送，请勿回复。\n");
        content.append("发送时间：").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        
        sendSimpleEmail(emailDto.getToEmail(), subject, content.toString());
    }
    
    /**
     * 发送系统异常提醒邮件
     * @param emailDto 邮件数据传输对象
     */
    @Async
    public void sendSystemAlertEmail(EmailDto.SystemAlertEmailDto emailDto) {
        String subject = "【AI聊天系统】系统异常提醒";
        
        StringBuilder content = new StringBuilder();
        content.append("尊敬的管理员：\n\n");
        content.append("系统检测到异常，请及时处理。\n\n");
        content.append("异常详情：\n");
        content.append("--------------------------------------------------\n");
        content.append("异常级别：").append(emailDto.getAlertLevel()).append("\n");
        content.append("异常类型：").append(emailDto.getAlertType()).append("\n");
        content.append("异常时间：").append(emailDto.getAlertTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        content.append("异常描述：").append(emailDto.getAlertDescription()).append("\n");
        
        if (emailDto.getComponentName() != null && !emailDto.getComponentName().isEmpty()) {
            content.append("组件名称：").append(emailDto.getComponentName()).append("\n");
        }
        
        if (emailDto.getAdditionalInfo() != null && !emailDto.getAdditionalInfo().isEmpty()) {
            content.append("附加信息：").append(emailDto.getAdditionalInfo()).append("\n");
        }
        
        content.append("--------------------------------------------------\n\n");
        content.append("请尽快检查相关服务和系统状态。\n\n");
        content.append("此邮件由系统自动发送，请勿回复。\n");
        content.append("发送时间：").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
        
        sendSimpleEmail(emailDto.getToEmail(), subject, content.toString());
    }
}